package top.yudoge.dogeeditor.app.utils

import com.google.gson.Gson
import top.yudoge.dogeeditor.llm.memory.SessionMemory
import top.yudoge.dogeeditor.llm.rewrite.SQLGenerate2ChainNode
import java.util.LinkedList

class ChatHistoryUtils {
    companion object {

        private const val HISTORY_HOLDER_KEY = "message:history"

        fun addChatHistory(sessionId: String, message: Message, sessionMemory: SessionMemory) {
            var historyHolder = getHistoryHolder(sessionId, sessionMemory)
            historyHolder.add(message)
            sessionMemory.put(sessionId, HISTORY_HOLDER_KEY, Gson().toJson(historyHolder))
        }

        fun listChatHistory(sessionId: String, sessionMemory: SessionMemory): List<Message> {
            return getHistoryHolder(sessionId, sessionMemory).history()
        }

        private fun getHistoryHolder(sessionId: String, sessionMemory: SessionMemory): HistoryMessageHolder {
            return sessionMemory.get(sessionId, HISTORY_HOLDER_KEY)?.let {
                Gson().fromJson(it, HistoryMessageHolder::class.java)
            } ?: HistoryMessageHolder()
        }
    }
}

class HistoryMessageHolder {

    private val max = 10
    private val history = LinkedList<Message>()

    fun add(message: Message) {
        if (history.size >= max) {
            history.removeFirst()
        }

        history.addLast(message)
    }

    fun history(): List<Message> {
        return history.toList()
    }
}

class Message (
    val type: String,
    val content: String
)
